package com.chen.root.enums;

import cn.hutool.core.lang.Assert;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池拒绝策略
 * @Author: ChenJinLong
 * @DateTime: 2023/8/28 14:22
 **/
@AllArgsConstructor
@Getter
public enum RejectedEnum {

    /**
     * 交由调用方运行
     */
    CallerRunsPolicy(1, new ThreadPoolExecutor.CallerRunsPolicy()),

    /**
     * 抛出异常
     */
    AbortPolicy(2, new ThreadPoolExecutor.AbortPolicy()),

    /**
     * 丢弃
     */
    DiscardPolicy(3, new ThreadPoolExecutor.DiscardPolicy()),

    /**
     * 丢弃队列中最老的任务
     */
    DiscardOldestPolicy(4, new ThreadPoolExecutor.DiscardOldestPolicy());

    private final Integer code;
    private final RejectedExecutionHandler rejectedExecutionHandler;

    public static RejectedExecutionHandler getByCode(Integer code){
        for (RejectedEnum anEnum : RejectedEnum.values()) {
            if (anEnum.code.equals(code)){
                return anEnum.rejectedExecutionHandler;
            }
        }
        Assert.isTrue(false, "拒绝策略 -> " + code + " 不存在!");
        return null;
    }
}
